package cn.yr.netty.handler;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import cn.yr.common.core.domain.entity.YrMessage;
import cn.yr.netty.MessageDispatcher;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@ChannelHandler.Sharable
public class NettyMessageHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    @Autowired
    private MessageDispatcher messageDispatcher;
    /**
     * 创建线程池
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) {
        YrMessage message = null;
        try {
            message = JSONUtil.toBean(msg.text(), YrMessage.class);
        } catch (Exception e) {
            sendErrorMessage(ctx, "JSON字符串转换出错！");
            e.printStackTrace();
            return;
        }
        if(ObjectUtil.isEmpty(message)){
            sendErrorMessage(ctx, "消息为空！");
            return;
        }
        if(ObjectUtil.isEmpty(message.getType())){
            sendErrorMessage(ctx, "未设置消息类型！");
            return;
        }
        YrMessage finalMessage = message;
        //异步执行
        ctx.channel().eventLoop().execute(()->{
            try {
                // 执行逻辑
                messageDispatcher.execute(finalMessage,ctx.channel());
            } catch (Exception ex) {
                System.out.println("发生异常" + ex.getMessage());
            }
        });
    }

    private void sendErrorMessage(ChannelHandlerContext ctx, String errorMsg) {
        ctx.channel().writeAndFlush(new TextWebSocketFrame(errorMsg));
    }
}
